<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}蓝猫探索 - 无人机智能体探索系统{% endblock %}</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36CFC9',
                        accent: '#722ED1',
                        neutral: '#86909C',
                        light: '#F2F3F5',
                        dark: '#1D2129'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .btn-primary {
                @apply bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 transition-all hover:shadow-md;
            }
            .btn-secondary {
                @apply bg-secondary text-white px-4 py-2 rounded-md hover:bg-secondary/90 transition-all hover:shadow-md;
            }
            .category-active {
                @apply bg-primary/10 text-primary font-medium;
            }
            .slide-in {
                animation: slideIn 0.6s ease-out forwards;
            }
            @keyframes slideIn {
                from {
                    opacity: 0;
                    transform: translateY(20px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }
        }
    </style>
    
    {% block extra_css %}{% endblock %}
</head>
<body class="bg-white text-dark font-sans">
    <!-- 导航栏 -->
    <header id="navbar" class="fixed top-0 left-0 right-0 bg-white shadow-sm z-50 transition-all duration-300">
        <div class="container mx-auto px-4">
            <div class="flex items-center justify-between h-16">
                <!-- Logo -->
                <a href="/" class="flex items-center space-x-2">
                    <i class="fa fa-drone text-primary text-2xl"></i>
                    <span class="text-xl font-bold text-primary">蓝猫探索</span>
                </a>
                
                <!-- 桌面端导航 -->
                <nav class="hidden md:flex items-center space-x-8">
                    <a href="#" class="text-dark hover:text-primary transition-colors">首页</a>
                    <a href="#" class="text-dark hover:text-primary transition-colors">产品</a>
                    <a href="#" class="text-dark hover:text-primary transition-colors">解决方案</a>
                    <a href="#" class="text-dark hover:text-primary transition-colors">关于我们</a>
                    <a href="#" class="text-dark hover:text-primary transition-colors">联系我们</a>
                </nav>
                
                <!-- 功能按钮区 -->
                <div class="flex items-center space-x-4">
                    <!-- 搜索按钮 -->
                    <button class="p-2 text-gray-600 hover:text-primary transition-colors hidden md:block">
                        <i class="fa fa-search"></i>
                    </button>
                    
                    <!-- 搜索框 - 桌面端 -->
                    <div class="hidden md:block relative">
                        <input type="text" id="searchInput" 
                            class="pl-10 pr-4 py-2 rounded-full border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary w-48 lg:w-64 transition-all"
                            placeholder="搜索商品...">
                        <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                        <button id="searchBtn" class="absolute right-2 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-primary">
                            <i class="fa fa-arrow-right"></i>
                        </button>
                    </div>
                    
                    <!-- 用户菜单 -->
                    <div class="relative">
                        <button id="userMenuBtn" class="p-2 text-gray-600 hover:text-primary transition-colors">
                            <i class="fa fa-user"></i>
                        </button>
                        <div id="userMenu" class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 hidden z-50">
                            <div id="user-info" class="px-4 py-2 text-sm text-gray-600 hidden">
                                <p>欢迎回来，<span id="username"></span></p>
                            </div>
                            <a href="/login" id="loginLink" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">登录</a>
                            <a href="/register" id="registerLink" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hidden">注册</a>
                            <a href="/profile" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hidden">个人中心</a>
                            <button id="logoutBtn" class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hidden">退出登录</button>
                        </div>
                    </div>
                    
                    <!-- 购物车按钮 -->
                    <button id="cartBtn" class="p-2 text-gray-600 hover:text-primary transition-colors relative">
                        <i class="fa fa-shopping-cart"></i>
                        <span id="cartCount" class="absolute -top-1 -right-1 bg-primary text-white text-xs rounded-full h-5 w-5 flex items-center justify-center">0</span>
                    </button>
                    
                    <!-- 移动端菜单按钮 -->
                    <button id="mobileMenuBtn" class="p-2 text-gray-600 hover:text-primary transition-colors md:hidden">
                        <i class="fa fa-bars"></i>
                    </button>
                </div>
            </div>
            
            <!-- 移动端搜索框 -->
            <div class="md:hidden py-3">
                <div class="relative">
                    <input type="text" id="mobileSearchInput" 
                        class="w-full pl-10 pr-10 py-2 rounded-full border border-gray-200 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                        placeholder="搜索商品...">
                    <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    <button id="mobileSearchBtn" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-primary">
                        <i class="fa fa-arrow-right"></i>
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 移动端菜单 -->
        <div id="mobileMenu" class="md:hidden bg-white border-t hidden">
            <div class="container mx-auto px-4 py-3">
                <nav class="flex flex-col space-y-3">
                    <a href="#" class="text-dark hover:text-primary transition-colors py-2 border-b border-gray-100">首页</a>
                    <a href="#" class="text-dark hover:text-primary transition-colors py-2 border-b border-gray-100">产品</a>
                    <a href="#" class="text-dark hover:text-primary transition-colors py-2 border-b border-gray-100">解决方案</a>
                    <a href="#" class="text-dark hover:text-primary transition-colors py-2 border-b border-gray-100">关于我们</a>
                    <a href="#" class="text-dark hover:text-primary transition-colors py-2">联系我们</a>
                </nav>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main>
        {% block content %}{% endblock %}
    </main>

    <!-- 页脚 -->
    <footer class="bg-dark text-white pt-12 pb-6">
        <div class="container mx-auto px-4">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
                <div>
                    <div class="flex items-center space-x-2 mb-4">
                        <i class="fa fa-drone text-primary text-2xl"></i>
                        <span class="text-xl font-bold">蓝猫探索</span>
                    </div>
                    <p class="text-gray-400 mb-4">专注于无人机智能体探索未知空间及自主路径规划的创新科技公司</p>
                    <div class="flex space-x-4">
                        <a href="#" class="text-gray-400 hover:text-primary transition-colors"><i class="fa fa-weibo"></i></a>
                        <a href="#" class="text-gray-400 hover:text-primary transition-colors"><i class="fa fa-wechat"></i></a>
                        <a href="#" class="text-gray-400 hover:text-primary transition-colors"><i class="fa fa-youtube"></i></a>
                        <a href="#" class="text-gray-400 hover:text-primary transition-colors"><i class="fa fa-linkedin"></i></a>
                    </div>
                </div>
                
                <div>
                    <h3 class="text-lg font-semibold mb-4">产品中心</h3>
                    <ul class="space-y-2">
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">探索无人机</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">路径规划系统</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">智能控制系统</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">数据分析平台</a></li>
                    </ul>
                </div>
                
                <div>
                    <h3 class="text-lg font-semibold mb-4">关于我们</h3>
                    <ul class="space-y-2">
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">公司简介</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">研发团队</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">新闻动态</a></li>
                        <li><a href="#" class="text-gray-400 hover:text-white transition-colors">加入我们</a></li>
                    </ul>
                </div>
                
                <div>
                    <h3 class="text-lg font-semibold mb-4">联系我们</h3>
                    <ul class="space-y-2">
                        <li class="flex items-start">
                            <i class="fa fa-map-marker mt-1 mr-3 text-primary"></i>
                            <span class="text-gray-400">北京市海淀区中关村科技园区</span>
                        </li>
                        <li class="flex items-center">
                            <i class="fa fa-phone mr-3 text-primary"></i>
                            <span class="text-gray-400">400-123-4567</span>
                        </li>
                        <li class="flex items-center">
                            <i class="fa fa-envelope mr-3 text-primary"></i>
                            <span class="text-gray-400">contact@lanmao.com</span>
                        </li>
                    </ul>
                </div>
            </div>
            
            <div class="border-t border-gray-800 mt-8 pt-6 text-center text-gray-500 text-sm">
                <p>© 2023 蓝猫探索科技有限公司 版权所有</p>
            </div>
        </div>
    </footer>

    <!-- 购物车侧边栏 -->
    <div id="cartSidebar" class="fixed top-0 right-0 h-full w-full md:w-96 bg-white shadow-2xl z-50 transform translate-x-full transition-transform duration-300">
        <div class="h-full flex flex-col">
            <div class="p-4 border-b flex justify-between items-center">
                <h3 class="text-xl font-bold">购物车</h3>
                <button id="closeCartBtn" class="p-2 text-gray-500 hover:text-primary">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            
            <div id="cartItems" class="flex-1 overflow-y-auto p-4 space-y-4">
                <!-- 购物车为空状态 -->
                <div id="emptyCart" class="h-full flex flex-col items-center justify-center text-center">
                    <i class="fa fa-shopping-cart text-5xl text-gray-300 mb-4"></i>
                    <p class="text-gray-500 mb-4">您的购物车还是空的</p>
                    <button id="startShoppingBtn" class="btn-primary">
                        开始购物
                    </button>
                </div>
                
                <!-- 购物车商品将通过JavaScript动态加载 -->
            </div>
            
            <div class="p-4 border-t">
                <div class="flex justify-between mb-4">
                    <span class="font-medium">总计:</span>
                    <span id="cartTotal" class="font-bold text-xl">¥0.00</span>
                </div>
                <button id="checkoutBtn" class="btn-primary w-full disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                    结算
                </button>
            </div>
        </div>
    </div>

    <!-- 遮罩层 -->
    <div id="overlay" class="fixed inset-0 bg-black/50 z-40 hidden transition-opacity duration-300"></div>

    <!-- 快速查看模态框 -->
    <div id="quickViewModal" class="fixed inset-0 z-50 flex items-center justify-center hidden">
        <div class="absolute inset-0 bg-black/50" id="quickViewOverlay"></div>
        <div class="bg-white rounded-lg shadow-2xl w-full max-w-4xl max-h-[90vh] overflow-y-auto relative z-10 transform transition-all">
            <button id="closeQuickViewBtn" class="absolute top-4 right-4 w-8 h-8 flex items-center justify-center rounded-full bg-white/80 backdrop-blur-sm text-gray-600 hover:text-primary z-20">
                <i class="fa fa-times"></i>
            </button>
            
            <div class="p-4 md:p-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- 商品图片 -->
                    <div class="bg-gray-50 rounded-lg p-4 flex items-center justify-center">
                        <img id="quickViewImage" src="https://picsum.photos/id/26/600/600" alt="商品图片" class="max-h-96 object-contain">
                    </div>
                    
                    <!-- 商品信息 -->
                    <div>
                        <span id="quickViewCategory" class="text-sm text-primary bg-primary/10 px-2 py-1 rounded-full">电子产品</span>
                        <h3 id="quickViewTitle" class="text-2xl font-bold mt-2 mb-2">无人机智能探索系统</h3>
                        
                        <div class="flex items-center mb-4">
                            <div id="quickViewRating" class="flex text-yellow-400">
                                <i class="fa fa-star"></i>
                                <i class="fa fa-star"></i>
                                <i class="fa fa-star"></i>
                                <i class="fa fa-star"></i>
                                <i class="fa fa-star-half-alt"></i>
                            </div>
                            <span id="quickViewReviews" class="text-gray-500 text-sm ml-2">(120 评价)</span>
                        </div>
                        
                        <div id="quickViewPrice" class="text-3xl font-bold text-primary mb-6">¥2999.00</div>
                        
                        <p id="quickViewDescription" class="text-gray-600 mb-6">
                            高性能无人机智能探索系统，具备自主路径规划能力，可用于未知空间探索、救援探测等多种场景，配备高清摄像头和先进传感器。
                        </p>
                        
                        <!-- 数量选择 -->
                        <div class="mb-6">
                            <label class="block text-gray-700 mb-2">数量</label>
                            <div class="flex items-center w-32 border rounded-md">
                                <button id="quickViewDecreaseQty" class="w-10 h-10 flex items-center justify-center text-gray-600 hover:bg-gray-100">
                                    <i class="fa fa-minus"></i>
                                </button>
                                <input type="number" id="quickViewQty" value="1" min="1" class="w-12 h-10 text-center border-x focus:outline-none">
                                <button id="quickViewIncreaseQty" class="w-10 h-10 flex items-center justify-center text-gray-600 hover:bg-gray-100">
                                    <i class="fa fa-plus"></i>
                                </button>
                            </div>
                        </div>
                        
                        <!-- 操作按钮 -->
                        <div class="flex flex-col sm:flex-row gap-4">
                            <button id="quickViewAddToCart" class="btn-primary flex-1">
                                <i class="fa fa-shopping-cart mr-2"></i> 加入购物车
                            </button>
                            <a id="quickViewProductLink" href="#" class="btn-secondary flex-1 text-center py-2">
                                <i class="fa fa-eye mr-2"></i> 查看详情
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 提示框 -->
    <div id="toast" class="fixed bottom-6 left-1/2 transform -translate-x-1/2 bg-dark text-white px-6 py-3 rounded-full shadow-lg z-50 hidden transition-all duration-300 opacity-0">
        <span id="toastMessage">操作成功</span>
    </div>

    <!-- 公共JavaScript -->
    <script>
        // 全局通用功能
        document.addEventListener('DOMContentLoaded', function() {
            // 用户菜单切换
            const userMenuBtn = document.getElementById('userMenuBtn');
            const userMenu = document.getElementById('userMenu');
            
            if (userMenuBtn && userMenu) {
                userMenuBtn.addEventListener('click', function(e) {
                    e.stopPropagation();
                    userMenu.classList.toggle('hidden');
                });
                
                // 点击其他区域关闭用户菜单
                document.addEventListener('click', function() {
                    userMenu.classList.add('hidden');
                });
                
                userMenu.addEventListener('click', function(e) {
                    e.stopPropagation();
                });
            }
            
            // 显示提示框
            window.showToast = function(message, type = 'success') {
                const toast = document.getElementById('toast');
                const toastMessage = document.getElementById('toastMessage');
                
                if (toast && toastMessage) {
                    toastMessage.textContent = message;
                    
                    // 设置提示框样式
                    toast.className = 'fixed bottom-6 left-1/2 transform -translate-x-1/2 px-6 py-3 rounded-full shadow-lg z-50 transition-all duration-300';
                    
                    if (type === 'success') {
                        toast.classList.add('bg-green-600', 'text-white');
                    } else if (type === 'error') {
                        toast.classList.add('bg-red-600', 'text-white');
                    } else if (type === 'warning') {
                        toast.classList.add('bg-yellow-500', 'text-dark');
                    }
                    
                    toast.classList.remove('hidden', 'opacity-0');
                    toast.classList.add('opacity-100');
                    
                    // 3秒后隐藏
                    setTimeout(() => {
                        toast.classList.remove('opacity-100');
                        toast.classList.add('opacity-0');
                        setTimeout(() => {
                            toast.classList.add('hidden');
                        }, 300);
                    }, 3000);
                }
            };
            
            // 检查登录状态
            window.checkAuth = async function() {
                const accessToken = localStorage.getItem('access_token');
                const userMenu = document.getElementById('userMenu');
                const loginLink = document.getElementById('loginLink');
                const registerLink = document.getElementById('registerLink');
                const userInfo = document.getElementById('user-info');
                const username = document.getElementById('username');
                const logoutBtn = document.getElementById('logoutBtn');
                
                if (!userMenu || !loginLink || !registerLink || !userInfo || !username || !logoutBtn) {
                    return false;
                }
                
                if (accessToken) {
                    try {
                        // 验证token有效性
                        const response = await fetch('http://192.168.10.124:8000/auth/me/', {
                            headers: {
                                'Authorization': `Bearer ${accessToken}`
                            }
                        });
                        
                        if (response.ok) {
                            const userData = await response.json();
                            currentUser = userData;
                            username.textContent = userData.username || '用户';
                            
                            // 更新UI显示
                            loginLink.classList.add('hidden');
                            registerLink.classList.add('hidden');
                            userInfo.classList.remove('hidden');
                            logoutBtn.classList.remove('hidden');
                            
                            return true;
                        } else {
                            // Token无效，清除本地存储
                            localStorage.removeItem('access_token');
                            throw new Error('Token invalid');
                        }
                    } catch (error) {
                        console.error('Auth check failed:', error);
                        currentUser = null;
                    }
                }
                
                // 未登录状态
                loginLink.classList.remove('hidden');
                registerLink.classList.remove('hidden');
                userInfo.classList.add('hidden');
                logoutBtn.classList.add('hidden');
                return false;
            };
            
            // 登出功能
            window.logout = function() {
                localStorage.removeItem('access_token');
                currentUser = null;
                cart = [];
                updateCartUI();
                checkAuth();
                showToast('已成功登出');
                
                // 隐藏用户菜单
                const userMenu = document.getElementById('userMenu');
                if (userMenu) {
                    userMenu.classList.add('hidden');
                }
            };
            
            // 购物车侧边栏控制
            window.openCartSidebar = function() {
                const cartSidebar = document.getElementById('cartSidebar');
                const overlay = document.getElementById('overlay');
                
                if (cartSidebar && overlay) {
                    cartSidebar.classList.remove('translate-x-full');
                    overlay.classList.remove('hidden');
                    document.body.style.overflow = 'hidden';
                }
            };
            
            window.closeCartSidebar = function() {
                const cartSidebar = document.getElementById('cartSidebar');
                const overlay = document.getElementById('overlay');
                
                if (cartSidebar && overlay) {
                    cartSidebar.classList.add('translate-x-full');
                    overlay.classList.add('hidden');
                    document.body.style.overflow = '';
                }
            };
            
            // 移动端菜单控制
            window.toggleMobileMenu = function() {
                const mobileMenu = document.getElementById('mobileMenu');
                if (mobileMenu) {
                    mobileMenu.classList.toggle('hidden');
                }
            };
            
            // 关闭快速查看模态框
            window.closeQuickViewModal = function() {
                const quickViewModal = document.getElementById('quickViewModal');
                if (quickViewModal) {
                    quickViewModal.classList.add('hidden');
                    document.body.style.overflow = '';
                }
            };
            
            // 更新购物车UI
            window.updateCartUI = function() {
                const cartCount = document.getElementById('cartCount');
                const cartItems = document.getElementById('cartItems');
                const emptyCart = document.getElementById('emptyCart');
                const cartTotal = document.getElementById('cartTotal');
                const checkoutBtn = document.getElementById('checkoutBtn');
                
                if (!cartCount || !cartItems || !emptyCart || !cartTotal || !checkoutBtn) {
                    return;
                }
                
                // 更新购物车数量
                const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
                cartCount.textContent = totalItems;
                
                // 更新购物车内容
                if (cart.length === 0) {
                    emptyCart.classList.remove('hidden');
                    cartItems.innerHTML = '';
                    checkoutBtn.disabled = true;
                    cartTotal.textContent = '¥0.00';
                    return;
                }
                
                emptyCart.classList.add('hidden');
                checkoutBtn.disabled = false;
                
                // 计算总价
                let total = 0;
                cartItems.innerHTML = '';
                
                // 添加购物车商品
                cart.forEach(item => {
                    total += item.price * item.quantity;
                    
                    const cartItemElement = document.createElement('div');
                    cartItemElement.className = 'flex border-b pb-4';
                    cartItemElement.innerHTML = `
                        <img src="${item.image}" alt="${item.name}" class="w-20 h-20 object-cover rounded-md">
                        <div class="ml-4 flex-1">
                            <h4 class="font-medium">${item.name}</h4>
                            <p class="text-primary font-bold mt-1">¥${item.price.toFixed(2)}</p>
                            <div class="flex items-center mt-2">
                                <button class="decrease-qty w-6 h-6 flex items-center justify-center rounded border text-gray-600" data-id="${item.id}">
                                    <i class="fa fa-minus text-xs"></i>
                                </button>
                                <span class="mx-2">${item.quantity}</span>
                                <button class="increase-qty w-6 h-6 flex items-center justify-center rounded border text-gray-600" data-id="${item.id}">
                                    <i class="fa fa-plus text-xs"></i>
                                </button>
                                <button class="remove-item ml-auto text-gray-400 hover:text-red-500" data-id="${item.id}">
                                    <i class="fa fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    `;
                    
                    cartItems.appendChild(cartItemElement);
                });
                
                // 更新总价
                cartTotal.textContent = `¥${total.toFixed(2)}`;
                
                // 添加购物车项目事件监听
                document.querySelectorAll('.decrease-qty').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const productId = this.dataset.id;
                        updateCartItemQuantity(productId, -1);
                    });
                });
                
                document.querySelectorAll('.increase-qty').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const productId = this.dataset.id;
                        updateCartItemQuantity(productId, 1);
                    });
                });
                
                document.querySelectorAll('.remove-item').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const productId = this.dataset.id;
                        removeFromCart(productId);
                    });
                });
            };
            
            // 更新购物车商品数量
            window.updateCartItemQuantity = function(productId, change) {
                const itemIndex = cart.findIndex(item => item.id === productId);
                
                if (itemIndex !== -1) {
                    cart[itemIndex].quantity += change;
                    
                    // 如果数量为0，从购物车移除
                    if (cart[itemIndex].quantity <= 0) {
                        cart.splice(itemIndex, 1);
                        showToast('商品已从购物车移除');
                    } else {
                        showToast('购物车已更新');
                    }
                    
                    // 保存到服务器
                    saveCart();
                    // 更新UI
                    updateCartUI();
                }
            };
            
            // 从购物车移除商品
            window.removeFromCart = function(productId) {
                const initialLength = cart.length;
                cart = cart.filter(item => item.id !== productId);
                
                if (cart.length < initialLength) {
                    showToast('商品已从购物车移除');
                    // 保存到服务器
                    saveCart();
                    // 更新UI
                    updateCartUI();
                }
            };
            
            // 添加到购物车
            window.addToCart = function(productId, quantity = 1) {
                // 查找商品信息
                const product = products.find(p => p.id === productId);
                if (!product) return;
                
                // 检查商品是否已在购物车中
                const existingItemIndex = cart.findIndex(item => item.id === productId);
                
                if (existingItemIndex !== -1) {
                    // 更新数量
                    cart[existingItemIndex].quantity += quantity;
                } else {
                    // 添加新商品
                    cart.push({
                        id: product.id,
                        name: product.name,
                        price: product.price,
                        image: product.image,
                        quantity: quantity
                    });
                }
                
                showToast('已添加到购物车');
                // 保存到服务器
                saveCart();
                // 更新UI
                updateCartUI();
            };
            
            // 保存购物车到服务器
            window.saveCart = async function() {
                if (!accessToken) return;
                
                try {
                    await fetch('http://192.168.10.124:8000/cart/', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${accessToken}`
                        },
                        body: JSON.stringify({ items: cart })
                    });
                } catch (error) {
                    console.error('Error saving cart:', error);
                }
            };
            
            // 过滤商品
            window.filterProducts = function(products) {
                return products.filter(product => {
                    // 分类过滤
                    const categoryMatch = currentCategory === 'all' || product.category === currentCategory;
                    
                    // 搜索过滤
                    const searchMatch = !currentSearch || 
                        product.name.toLowerCase().includes(currentSearch.toLowerCase()) ||
                        product.description.toLowerCase().includes(currentSearch.toLowerCase());
                    
                    return categoryMatch && searchMatch;
                });
            };
            
            // 渲染商品
            window.renderProducts = function(products) {
                if (!productsContainer) return;
                
                products.forEach(product => {
                    const productCard = document.createElement('div');
                    productCard.className = 'bg-white rounded-lg shadow-sm hover:shadow-md transition-shadow overflow-hidden group';
                    productCard.innerHTML = `
                        <div class="relative">
                            <img src="${product.image}" alt="${product.name}" class="w-full h-48 object-cover group-hover:scale-105 transition-transform duration-300">
                            <button class="quick-view-btn absolute top-2 right-2 bg-white/80 backdrop-blur-sm p-2 rounded-full text-gray-600 hover:text-primary" data-id="${product.id}">
                                <i class="fa fa-eye"></i>
                            </button>
                            ${product.discount > 0 ? `<span class="absolute top-2 left-2 bg-red-500 text-white text-xs px-2 py-1 rounded">${product.discount}% OFF</span>` : ''}
                        </div>
                        <div class="p-4">
                            <div class="text-sm text-gray-500 mb-1">${product.category}</div>
                            <h3 class="font-medium mb-2 line-clamp-2 h-12">${product.name}</h3>
                            <div class="flex items-center mb-2">
                                <div class="flex text-yellow-400 text-sm">
                                    ${Array(Math.floor(product.rating)).fill().map(() => '<i class="fa fa-star"></i>').join('')}
                                    ${product.rating % 1 >= 0.5 ? '<i class="fa fa-star-half-alt"></i>' : ''}
                                    ${Array(5 - Math.ceil(product.rating)).fill().map(() => '<i class="fa fa-star-o"></i>').join('')}
                                </div>
                                <span class="text-gray-500 text-xs ml-1">(${product.reviews} 评价)</span>
                            </div>
                            <div class="flex items-center justify-between">
                                <div class="font-bold text-primary">¥${product.price.toFixed(2)}</div>
                                <button class="add-to-cart-btn bg-primary/10 text-primary p-2 rounded-full hover:bg-primary hover:text-white transition-colors" data-id="${product.id}">
                                    <i class="fa fa-shopping-cart"></i>
                                </button>
                            </div>
                        </div>
                    `;
                    
                    productsContainer.appendChild(productCard);
                });
                
                // 添加事件监听
                document.querySelectorAll('.add-to-cart-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const productId = this.dataset.id;
                        addToCart(productId);
                    });
                });
                
                document.querySelectorAll('.quick-view-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const productId = this.dataset.id;
                        openQuickView(productId);
                    });
                });
            };
            
            // 打开快速查看
            window.openQuickView = function(productId) {
                const product = products.find(p => p.id === productId);
                if (!product) return;
                
                currentQuickViewProductId = productId;
                
                // 更新快速查看模态框内容
                quickViewImage.src = product.image;
                quickViewImage.alt = product.name;
                quickViewTitle.textContent = product.name;
                quickViewCategory.textContent = product.category;
                quickViewPrice.textContent = `¥${product.price.toFixed(2)}`;
                quickViewDescription.textContent = product.description;
                quickViewReviews.textContent = `(${product.reviews} 评价)`;
                quickViewQty.value = 1;
                quickViewProductLink.href = `/product/${productId}`;
                
                // 更新评分星星
                quickViewRating.innerHTML = '';
                for (let i = 0; i < 5; i++) {
                    const star = document.createElement('i');
                    if (i < Math.floor(product.rating)) {
                        star.className = 'fa fa-star';
                    } else if (i < product.rating) {
                        star.className = 'fa fa-star-half-alt';
                    } else {
                        star.className = 'fa fa-star-o';
                    }
                    quickViewRating.appendChild(star);
                }
                
                // 显示模态框
                quickViewModal.classList.remove('hidden');
                document.body.style.overflow = 'hidden';
            };
        });
    </script>
    
    {% block extra_js %}{% endblock %}
</body>
</html>
